<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      .wrapper {
        margin: 0 auto;
        height: 600px;
        width: 600px;
        display: flex;
        position: relative;
        flex-wrap: wrap;
      }
      .item {
        width: 200px;
        height: 200px;
        border: 1px solid red;
        box-sizing: border-box;
        cursor: pointer;
      }
      .button-wrapper {
        display: flex;
        justify-content: center;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
      <div class="item">6</div>
      <div class="item">7</div>
      <div class="item">8</div>
      <div class="item">9</div>
    </div>
    <div class="button-wrapper">
      <button id="start">开始</button>
      <button id="end">结束</button>
    </div>
  </body>
  <script>
    // 获取item
    const items = document.querySelectorAll(".item");
    // 获取start按钮
    const start = document.getElementById("start");
    // 颜色数组
    const colors = [
      "red",
      "green",
      "blue",
      "yellow",
      "pink",
      "purple",
      "orange",
      "black",
    ];
    // 返回随机颜色
    function randomColor() {
      // Math.random() 生成一个0-1之间的随机数
      // Math.floor() 向下取整
      // colors.length 为颜色数组的长度
      // Math.floor(Math.random() * colors.length) 生成一个0-colors.length之间的随机数
      return colors[Math.floor(Math.random() * colors.length)];
    }
    // 定义定时器，方便取消
    let timer;
    // nowIndex放在外面，方便开始
    let nowIndex = 0;
    function startFn() {
      timer = setInterval(() => {
        items[nowIndex].style.backgroundColor = randomColor();
        nowIndex === 0
          ? (items[items.length - 1].style.backgroundColor = "inherit")
          : (items[nowIndex - 1].style.backgroundColor = "inherit");
        nowIndex++;
        console.log(nowIndex);
        if (nowIndex === items.length) {
          nowIndex = 0;
        }
      }, 500);
    }
    // 停止定时器
    function endFn() {
      clearInterval(timer);
    }
    // 添加事件监听
    end.addEventListener("click", endFn);
    start.addEventListener("click", startFn);
    // setInterval方法会返回当前定时器的id，可以使用clearInterval(id)来取消定时器
    timer = setInterval(() => {
      console.log("这里的方法一秒钟会执行一次");
    }, 1000);
    // 使用clearInterval(timer)可以取消定时器
    clearInterval(timer);
  </script>
</html>
